import React, { useState, useEffect, useContext } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Input,
  Form,
  Grid,
  Message,
  Tag,
  Modal,
  Switch,
} from '@arco-design/web-react';
import dayjs from 'dayjs';
import { GlobalContext } from '@/context';
import {
  IconSearch,
  IconPlus,
  IconRefresh,
  IconDelete,
  IconInfoCircle,
  IconCheck,
  IconClose,
  IconEdit,
} from '@arco-design/web-react/icon';
import styles from './style/index.module.less';
import './mock';
import { getTagsList, delTags, editTags, updateStatus } from '@/api/tags';
import AddModal from './addModal';
import { EditableCell, EditableRow } from './edit';

function Tags() {
  const { Row, Col } = Grid;
  const { useForm } = Form;
  const [form] = useForm();
  const { lang } = useContext(GlobalContext);
  const colSpan = lang === 'zh-CN' ? 8 : 12;
  const [selectRow, setSelectRow] = useState({});

  // 表头
  const columns = [
    {
      title: 'ID',
      dataIndex: '_id',
    },
    {
      title: '标签名称',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: '文章数量',
      dataIndex: 'articleNum',
    },
    {
      title: '是否启用',
      dataIndex: 'status',
      render: (_, record) => (
        <Switch
          checkedIcon={<IconCheck />}
          checked={record.status}
          uncheckedIcon={<IconClose />}
          onChange={(checked) => {
            changeStatus(checked, record);
          }}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (x) => dayjs(x).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      render: (x) => (x ? dayjs(x).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },
    {
      title: '操作',
      dataIndex: 'operations',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            icon={<IconEdit />}
            onClick={() => {
              editClick(record);
            }}
          ></Button>
          <Button
            type="primary"
            status="danger"
            icon={<IconDelete />}
            onClick={() => {
              deleteClick(record);
            }}
          ></Button>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  // 获取表格数据
  async function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    const params = {
      page: current,
      pageSize,
      ...formParams,
    };
    try {
      const res: any = await getTagsList(params);
      if (res.code === 200) {
        setData(res.data.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.total,
        });
        setLoading(false);
      } else {
      }
    } catch (error) {
      console.error(error);
    }
  }

  // 分页
  function onChangeTable(pagination) {
    setPatination(pagination);
  }

  // 查询
  function handleSearch() {
    setFormParams(form.getFields());
    fetchData()
  }

  // 重置
  const handleReset = () => {
    form.resetFields();
  };

  // 新建
  const addClick = () => {
    setSelectRow({ add: true });
    setAddModalVisible(true);
  };

  //编辑
  const onHandleSave = async (row) => {
    const res: any = await editTags({ id: row._id, name: row.name });
    if (res.code === 200) {
      Message.success(res.msg);
      fetchData();
    } else {
      Message.error('修改失败，请重试！');
    }
  };

  // 编辑
  const editClick = (record) => {
    setSelectRow(record);
    setAddModalVisible(true);
  };

  // 删除
  const deleteClick = (record) => {
    if (record.status) {
      Message.warning('启用状态不可删除');
      return false;
    }
    const id = record._id;
    Modal.confirm({
      title: '提示',
      content: `确认删除 <${record.name}>？`,
      okButtonProps: { status: 'danger' },
      onOk: async () => {
        try {
          const res: any = await delTags({ id });
          if (res.code === 200) {
            Message.success(res.msg);
            fetchData();
          } else {
            Message.error(res.msg);
          }
        } catch (error) {
          console.error(error);
        }
      },
    });
  };

  // 是否启用
  const changeStatus = async (status: boolean, row) => {
    setLoading(true);
    try {
      const res: any = await updateStatus({ id: row._id, status });
      if (res.code === 200) {
        Message.success(res.msg);
        fetchData();
      } else {
        Message.error('修改失败，请重试！');
        setLoading(false);
      }
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div>
      <Card
        title="标签列表"
        headerStyle={{ border: 'none', height: 'auto', paddingTop: '20px' }}
      >
        <div className={styles['search-form-wrapper']}>
          <Form
            form={form}
            className={styles['search-form']}
            labelAlign="left"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
          >
            <Row gutter={24}>
              <Col span={colSpan}>
                <Form.Item label="标签名称" field="name">
                  <Input placeholder="请输入标签名称" allowClear />
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <div className={styles['right-button']}>
            <Space>
              <Button
                type="primary"
                icon={<IconSearch />}
                onClick={handleSearch}
              >
                查询
              </Button>
              <Button icon={<IconRefresh />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </div>
        </div>
        <div className={styles['button-group']}>
          <Space>
            <Button type="primary" icon={<IconPlus />} onClick={addClick}>
              新建
            </Button>
          </Space>
          <Tag color="orangered" icon={<IconInfoCircle />}>
            点击标签名称可编辑
          </Tag>
        </div>
        <Table
          rowKey="_id"
          loading={loading}
          onChange={onChangeTable}
          pagination={pagination}
          columns={columns.map((column) =>
            column.editable
              ? {
                  ...column,
                  onCell: () => ({
                    onHandleSave,
                  }),
                }
              : column
          )}
          components={{
            body: {
              row: EditableRow,
              cell: EditableCell,
            },
          }}
          data={data}
        />
      </Card>
      <AddModal
        changeVisible={setAddModalVisible}
        propsVisible={addModalVisible}
        fetchData={fetchData}
        selectRow={selectRow}
      />
    </div>
  );
}

export default Tags;
